package com.xy.compose.main

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.hilt.navigation.compose.hiltViewModel
import com.xy.compose.main.view.NavBottom
import com.xy.compose.main.viewmodel.MainViewModel
import com.xy.compose.resource_libs.ThemeBackground
import kotlinx.coroutines.launch

@Composable
internal fun MainRoute(viewModel: MainViewModel = hiltViewModel()) {


}

@Composable
fun MainScreen(currentPageIndex: Int = 0, onPageChanged: (Int) -> Unit = {}) {
    // 协程作用域
    val scope = rememberCoroutineScope()
    val pagerState = rememberPagerState(initialPage = 0) { 4 }
    // 监听页面变化
    LaunchedEffect(pagerState) {
        snapshotFlow { pagerState.currentPage }.collect { page ->
            onPageChanged(page)
        }
    }

    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(ThemeBackground),
        contentAlignment = Alignment.BottomCenter
    ) {
        HorizontalPager(userScrollEnabled = true, state = pagerState, modifier = Modifier.fillMaxSize()) {
            when (it) {
                0 -> Box(
                    Modifier
                        .fillMaxSize()
                        .background(Color.Green)
                )

                1 -> Box(
                    Modifier
                        .fillMaxSize()
                        .background(Color.Red)
                )

                2 -> Box(
                    Modifier
                        .fillMaxSize()
                        .background(Color.Blue)
                )
            }
        }
        NavBottom(currentPageIndex,{index ->
            scope.launch {
                pagerState.animateScrollToPage(index)
            }
        })
    }
}



